package com.interesting.client.UI.setting;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.interesting.MainActivity;
import com.interesting.R;
import com.interesting.base.core.BaseActivity;
import com.interesting.base.http.HttpUtil;
import com.interesting.base.utils.Constant;
import com.interesting.client.UI.commonActivity.UIUtil;
import com.interesting.client.application.AppHolder;

/** 登录界面 */
public class LoginActivity extends BaseActivity implements OnClickListener {

	private TextView register;
	private LinearLayout layout;
	private EditText username, password;
	private Button login;
	private SharedPreferences sp;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting_login_activity);

		getSupportActionBar().setCustomView(R.layout.text_actionbar_custom_view);
		setTitle(getResources().getString(R.string.login_title));

		initView();

		register.setOnClickListener(this);
		login.setOnClickListener(this);

	}

	private void initView() {
		register = (TextView) findViewById(R.id.setting_login_activity_toregister);
		layout = (LinearLayout) findViewById(R.id.setting_login_activity_layout);
		username = (EditText) findViewById(R.id.setting_login_activity_username);
		password = (EditText) findViewById(R.id.setting_login_activity_password);
		login = (Button) findViewById(R.id.setting_login_activity_login);

		register.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);// 下划线

		// 读取已保存的用户名 及密码

		sp = getSharedPreferences(Constant.SHARE_PREFERENCE, Activity.MODE_PRIVATE);
		username.setText(sp.getString(Constant.USERNAME, ""));
		String pwd = sp.getString(Constant.PASSWORD, "");

		password.setText(pwd);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.setting_login_activity_toregister: // 注册
			Intent toRegister = new Intent(LoginActivity.this, RegisterActivity.class);
			startActivity(toRegister);
			LoginActivity.this.finish();
			break;
		case R.id.setting_login_activity_login: // 登录
			toLogin(username.getText().toString(), password.getText().toString());
			break;
		}
	}

	/** 登录时 首先 检查用户名 ，密码 是否为空 符合条件在登录 */
	private void toLogin(String username, String password) {
		if (username.equals("") || password.equals("")) {
			rock();
		} else {
			UIUtil.showWaitDialog(getSupportFragmentManager());
			new LoginAsyncTask().execute(username, password);
		}
	}

	/** 动画 */
	private void rock() {
		TranslateAnimation rock = new TranslateAnimation(-7, 7, 0, 0);
		rock.setDuration(100);
		rock.setRepeatCount(6);
		rock.setRepeatMode(Animation.REVERSE);
		layout.startAnimation(rock);
	}

	private void toIntent(boolean LoggedIn) {
		Intent toMenu = new Intent(LoginActivity.this, MainActivity.class);
		toMenu.putExtra("LoggedIn", LoggedIn);
		LoginActivity.this.setResult(10, toMenu);
		LoginActivity.this.finish();
	}

	/** 登录异步 */
	class LoginAsyncTask extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			Map<String, String> request = new HashMap<String, String>();
			request.put("act", "login");
			request.put("username", params[0]);
			request.put("password", params[1]);
			return HttpUtil.post(request);
		}

		@Override
		protected void onPostExecute(String result) {
			JSONObject response = HttpUtil.parseResult(result);
			if (response != null) {

				UIUtil.hideDialog(getSupportFragmentManager());
				// 如果结果不为空 则保存用户名 密码 到本地
				SharedPreferences input = getSharedPreferences(Constant.SHARE_PREFERENCE, Activity.MODE_PRIVATE);
				SharedPreferences.Editor input_editor = input.edit();
				input_editor.putString(Constant.USERNAME, username.getText().toString());
				try {
					input_editor.putString(Constant.PASSWORD, password.getText().toString());
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				input_editor.commit();
				try {
					JSONObject userdata = response.getJSONObject("userData");
					AppHolder.getInsatnce().user.setUserId(userdata.getString("userId"));
					AppHolder.getInsatnce().user.setUserName(userdata.getString("username"));
					AppHolder.getInsatnce().user.setUserIcon(userdata.getString("icon"));
				} catch (JSONException e) {
					e.printStackTrace();
				}
				toIntent(true);
			} else {
				UIUtil.hideDialog(getSupportFragmentManager());
				UIUtil.showToast(getApplicationContext(), "登录失败");
			}

			super.onPostExecute(result);
		}
	}

}
